package com.ren.service.core.handler.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ren.service.core.mapper.DictMapper;
import com.ren.service.core.model.bo.ExcelDictBO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author RenGaoshuai
 * @date 2023/8/7 17:05
 * @description
 */
@Slf4j
//@AllArgsConstructor //全参
@NoArgsConstructor //无参
public class ExcelDictBOListener extends AnalysisEventListener<ExcelDictBO> {

    /**
     * 5条存储1次，清除list
     */
    private static final int BATCH_COUNT = 5;
    List<ExcelDictBO> list = new ArrayList();

    private DictMapper dictMapper;

    public ExcelDictBOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    /**
     *遍历每一行的记录
     * @param excelDictBO
     * @param context
     */
    @Override
    public void invoke(ExcelDictBO excelDictBO, AnalysisContext context) {
        log.info("解析到一条记录: {}", excelDictBO);
        list.add(excelDictBO);

        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() > BATCH_COUNT){
            saveData();

            list.clear();;
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        dictMapper.insertBatch(list);  //批量插入
        log.info("存储数据库成功！");
    }
}
